//
//  ViewController.m
//  JiSuWoNiu
//
//  Created by 文道江 on 16/4/21.
//  Copyright © 2016年 DaoJiang. All rights reserved.
//

#import "ViewController.h"
#import "WebViewController.h"
#import "UpgradeManger.h"

@interface ViewController ()

@property (strong, nonatomic) NSString *openUrl;
@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) NSURL *url;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setUserAgent];
    
    //设置默认加载URL
    //self.url = [NSURL URLWithString:[@"file://" stringByAppendingFormat:@"%@", [FZEasyFile fullFileName:@"web/index.html"]]];
    self.url = [NSURL URLWithString:[UpgradeManger getWebAppUrl]];
    //self.url = [NSURL URLWithString:@"http://192.168.1.10:8081/"];
    // Do any additional setup after loading the view, typically from a nib.
    
    _webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    _webView.scrollView.bounces = NO;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    HybridBridge *bridge = [HybridBridge bridgeForWebView:_webView webViewDelegate:self controller:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"........... %@", data);
    }];
    
    // 加载插件
    [bridge loadPlugin:@"BaiduMTJ"];
    [bridge loadPlugin:@"Social"];
    [bridge loadPlugin:@"GeTui"];
    [bridge loadPlugin:@"UpgradeSplash"];
    
    [self subscribePushMessage]; //处理推送消息
    
    
    [self.view addSubview: _webView];
    
    [NSThread sleepForTimeInterval:0.2];
    if (_openUrl == nil){
        [self loadWebApp];
    }else{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_openUrl]];
        [_webView loadRequest:request];
    }
    
#ifdef DEBUG
    //DEBUG 模式处理 ftp
    [[HybridEventBus defaultEventBus] subscribe:@"ftpReceiveFileListChanged" UsingBlock:^(NSNotification *notification) {
        NSLog(@"ftpCloseConnection %@", _webView);
        dispatch_async(dispatch_get_main_queue(), ^(){
            [_webView reload];
        });
    }];
    
    [KSToastView ks_showToast:@"Run in debug mode"];
#endif
    
}

- (void)loadWebApp {
    
    /*if (![FZEasyFile isFileExists:@"web/webapp_version.txt"]){
     NSString *path = [[NSBundle mainBundle] pathForResource:@"web" ofType:@"zip"];
     if (path)[SSZipArchive unzipFileAtPath:path toDestination:[FZEasyFile fullFileName:@"web"]];
     }*/
    [self loadURL:self.url];
}

- (void)loadURL:(NSURL *)url{
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)loadHybridUrl:(NSString *)act{
    NSLog(@"%@",@"loadHybridUrl");
    _openUrl = [[self.url.absoluteString stringByAppendingString:@"#"] stringByAppendingString:act];
    NSURL *requestUrl = [NSURL URLWithString: _openUrl];
    NSLog(@"%@",_openUrl);
    NSURLRequest *requestHybridUrl = [NSURLRequest requestWithURL:requestUrl];
    [_webView loadRequest:requestHybridUrl];
}

- (NSString*) setUserAgent{
    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU %@ %@ like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/%@ MSNative %@", device.name, device.systemName,device.systemVersion, device.systemVersion, infoDictionary[@"CFBundleShortVersionString"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
    return userAgent;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UIWebViewDe

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.documentElement.style.webkitTouchCallout = \"none\";document.documentElement.style.webkitUserSelect='none';window.deviceWidth=%f;window.deviceHeight=%f;window.nativeReady=true;", webView.frame.size.width, webView.frame.size.height]];
}

#pragma mark 处理推送离线推送消息

- (void)subscribePushMessage{
    
    [[HybridEventBus defaultEventBus] subscribe:@"GeTuiSdkDidReceivePayload" UsingBlock:^(NSNotification *notification) {
        
        NSString *payloadMsg = notification.userInfo[@"payloadMsg"];
        
        //只处理离线消息
        if (notification.userInfo && [notification.userInfo[@"offLine"] boolValue]){
            
            NSLog(@"payload %@", notification.userInfo);
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
            
            dispatch_async(dispatch_get_main_queue(), ^(){
                
                // 处理带 CMD 的推送消息
                if (dictionary && dictionary[@"cmd"]){
                    
                    NSString *cmd = dictionary[@"cmd"];
                    if ([cmd isEqualToString:@"hybrid"]){
                        
                        _openUrl = [[self.url.absoluteString stringByAppendingString:@"#"] stringByAppendingString:dictionary[@"act"]];
                    }else if ([cmd isEqualToString:@"url"]){
                        
                        WebViewController *webViewController = [[WebViewController alloc] init];
                        [webViewController setOpenUrl:dictionary[@"act"]];
                        if (self.navigationController){
                            [self.navigationController pushViewController:webViewController animated:YES];
                        }else{
                            [self presentViewController:webViewController animated:YES completion:nil];
                        }
                    }
                }
            });
        }
        
    }];
}

@end